/*
 * @Author: mayijun
 * @Date: 2022-05-13 10:21:47
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-06 14:44:45
 */
//场景弹出框
import API from '@/services';
import { EDicType } from '@/utils/constants';
import { ElCol, ElDrawer, ElForm, ElFormItem, ElInput, ElMessage, ElOption, ElRow, ElSelect } from 'element-plus';
import { defineComponent, reactive, onMounted, ref, computed, watch, watchEffect } from 'vue';
import './index.scss';

const FetchDataDrawer = defineComponent({
  name: 'FetchDataDrawer',
  props: {
    drawerVisible: {
      type: Boolean,
      default: false
    },
    //1：创建2：编辑3：查看
    drawerType: {
      type: String,
      default: "1"
    },
    groupId: {
      type: Number,
      default: 0
    },
    id: {
      type: Number,
      default: 0
    },
  },
  emits: ['close'],
  setup: (props, { slots, attrs, emit }) => {


    const createFormRef: any = ref();
    const selectRef = ref();

    //卡片颜色数组
    const colorArray = ref([] as any[]);

    let indexForm = ref({
      cnName: "",
      description: "",
      sceneColorType: "",
      groupId: 0,
      id: null as any
    });

    /* 表单规则 */
    let rules: any = reactive({
      cnName: [
        {
          required: true,
          message: '请输入场景名称',
          trigger: 'blur'
        }
      ],
      description: [
        {
          required: true,
          message: '请输入场景备注语',
          trigger: 'blur'
        }
      ],
      sceneColorType: [
        {
          required: true,
          message: '请选择卡片颜色',
          trigger: 'change'
        }
      ],
    });

    const handleClose = () => {
      emit('close');
    }

    /* 查询卡片颜色 */
    const getCardColorList = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.sceneColorType
          });
        if (code === 200 && Array.isArray(data)) {
          colorArray.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    //保存筛选条件
    const confirmForm = async () => {
      createFormRef.value.validate(async (bol: Boolean) => {
        if (!bol) return;
        try {
          let state = null;
          if (props.drawerType == "1") {
            state = await API.scene.postScene(indexForm.value);
          } else {
            state = await API.scene.putSceneById({ id: indexForm.value.id }, indexForm.value);
          }

          if (state.code === 200) {
            ElMessage.success("保存成功");
            handleClose();
          }
        } catch (error) {
          console.log(error);
        }
      });
    }

    //查询详情
    const getFetchDataInfo = async () => {
      try {
        const { code, data }: any = await API.scene.getSceneById({ id: props.id });
        if (code === 200) {
          indexForm.value = {
            cnName: data.cnName,
            description: data.description,
            sceneColorType: data.sceneColorType,
            groupId: data.groupId,
            id: data.id
          };
          if (props.drawerType == "2") {
            changeSelect(data.sceneColorType);
          }
        }
      } catch (error) {
        console.log(error);
      }
    }

    //转换中文名称
    const getCnName = (code: any) => {
      switch (code) {
        case '1':
          return '创建场景';
        case '2':
          return '编辑场景';
        case '3':
          return '场景详情';
        default:
          return '';
      }
    }

    const changeSelect = (val: any) => {
      let parent = selectRef.value.$el.children[0].children[0].children[0];
      let obj = parent.children[0];
      //增加图的展示
      let bgColor = document.createElement("div");
      bgColor.setAttribute('class', 'select-bg-color');
      bgColor.setAttribute("style", `background-color: ${val}`);
      parent.append(bgColor);
      //隐藏原有的input，但保留站位
      obj.setAttribute("style", 'visibility: hidden;');
      obj.classList.add("avtive");
    }

    watch(
      () => props?.drawerVisible,
      () => {
        if (props?.drawerVisible) {
          indexForm.value.groupId = props.groupId;
          getCardColorList();
          //编辑和查看
          if (props.drawerType != "1") {
            getFetchDataInfo();
          }
          if (props.drawerType == "3") {
            rules = [];
          }
        }
      },
      {
        immediate: true
      }
    );

    return () => {
      return (
        <ElDrawer
          size="684"
          modelValue={props.drawerVisible}
          destroy-on-close={true}
          close-on-click-modal={false}
          append-to-body={true}
          title={getCnName(props.drawerType)}
          custom-class="system-drawer"
          onClosed={handleClose}
        >
          <div class="fetch-data-drawer">
            {props.drawerType == "3" && (<div class="fetch-data-title">基本信息:</div>)}
            <ElForm
              ref={createFormRef}
              model={indexForm.value}
              rules={rules}
              label-position={'right'}
              labelWidth={90}
            >
              <ElFormItem label="场景名称:" prop="cnName">
                {props.drawerType == "3" && (<span>{indexForm.value.cnName}</span>)}
                {props.drawerType != "3" && (<ElInput
                  size="large"
                  v-model={indexForm.value.cnName}
                ></ElInput>)}
              </ElFormItem>
              <ElFormItem label="场景备注语:" prop="description">
                {props.drawerType == "3" && (<span>{indexForm.value.description}</span>)}
                {props.drawerType != "3" && (<ElInput
                  size="large"
                  v-model={indexForm.value.description}
                ></ElInput>)}
              </ElFormItem>
              <ElFormItem label="卡片颜色:" prop="sceneColorType">
                {props.drawerType == "3" && (<div class="card-color" style={{ backgroundColor: indexForm.value.sceneColorType }}></div>)}
                {props.drawerType != "3" && (<ElSelect ref={selectRef} onChange={changeSelect} size="large" popper-class="drawer-card" v-model={indexForm.value.sceneColorType} placeholder="请选择卡片颜色">
                  {
                    colorArray.value.map((item: any) => (
                      <ElOption
                        key={item.label}
                        value={item.label}
                      >
                        <div class="card-color" style={{ backgroundColor: item.label }}></div>
                      </ElOption>
                    ))
                  }
                </ElSelect>)}
              </ElFormItem>
            </ElForm>
            {props.drawerType != "3" && (<div class="footer-btn">
              <el-button type="primary" onClick={() => confirmForm()}>
                确定
              </el-button>
            </div>)}
          </div >
        </ElDrawer>
      );
    };
  }
});

export default FetchDataDrawer;
